package octetString

import (
	"bytes"
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"unicode/utf8"
)

func EncodeFromStr(s string, length int) ([]byte, error) {
	// 计算字符串长度
	sl := utf8.RuneCountInString(s)
	if sl > length {
		return nil, fmt.Errorf("string length %d[%s] tag length %d", sl, s, length)
	}

	b := make([]byte, length)

	bytes, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(s))
	if err != nil {
		return nil, err
	}

	copy(b, bytes)

	return b, nil
}

func DecodeToStr(b []byte) (string, error) {
	gb, err := simplifiedchinese.GBK.NewDecoder().Bytes([]byte(b))
	if err != nil {
		return "", err
	}

	nb := bytes.ReplaceAll(gb, []byte{0}, []byte{32})
	nb = bytes.TrimSpace(nb)
	s := string(nb)

	if len(s) > 64 {
		s = s[:64]
	}

	return s, nil
}
